﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.IO.Ports;

namespace TCA_User
{
    public partial class Bill_List
    {
        DataTable Bill_List_dtb = new DataTable();
        DataSet Bill_List_ds = new DataSet();
        SqlDataAdapter Bill_List_da;
        DataTable Department_Cost = new DataTable();
        DataTable Total_Cost = new DataTable();

        const string ADMIN_LVL = "Admin";
        const string SUB_LVL = "Supervisor";
        const string OWNER_LVL = "Owner";
        const string MANAGER_LVL = "Manager";

        private void Create_Report_Table()
        {
            Department_Cost.Columns.Add("Card_Owner");
            Department_Cost.Columns.Add("Personal");
            Department_Cost.Columns.Add("Business");
            Department_Cost.Columns.Add("Total");

            Total_Cost.Columns.Add("Department");
            Total_Cost.Columns.Add("Personal");
            Total_Cost.Columns.Add("Business");
            Total_Cost.Columns.Add("Total");
        }

        private string Get_Cell_String(DataGridViewCell cell)
        {
            if (cell.Value != null)
            {
                return cell.Value.ToString().Trim();
            }
            return "";
        }
            
        private void Load_bill_List()
        {
            //BillTab_CardOwnerList
            string permission = User_Info.Permission.ToString().Trim();
            string card_id = "";
            string cards_depart = "";
            string card_user;
            string sql_cmd = @"SELECT * FROM dbo.Taxi_Bills_TBL";
            if (Share_DateTime.Checked == true)
            {
                sql_cmd = sql_cmd + " WHERE [Bill_date] BETWEEN '" + VS_dateTimePicker_From.Value.Date.ToString("dd MMM yy")
                          + "' AND '" + VS_dateTimePicker_To.Value.Date.ToString("dd MMM yy") + "'"; 
            }
            else
            {
                sql_cmd = sql_cmd + " WHERE (([Taxi_Provider_Name] = 'VinaSun' AND [Bill_date] BETWEEN '" + VS_dateTimePicker_From.Value.Date.ToString("dd MMM yy")
                                  + "' AND '" + VS_dateTimePicker_To.Value.Date.ToString("dd MMM yy") + "')"
                                  + " OR ([Taxi_Provider_Name] = 'MaiLinh' AND [Bill_date] BETWEEN '" + ML_dateTimePicker_From.Value.Date.ToString("dd MMM yy")
                                  + "' AND '" + ML_dateTimePicker_To.Value.Date.ToString("dd MMM yy") + "'))";
            }

            //@NOTE (Kien): Level 1
            //                  permission == SUB_LVL
            //                  permission == OWNER_LVL
            //                      ==> show Card of this user only
            //                  permission == MANAGER_LVL
            //                      ==> show Card of this deparment
            //                  permission == ADMIN_LVL && Show each card owner select
            //                      ==> View for cards in list only (List by Load_Card_List())
            //                  else ==> view for cards
            //              level 2:
            //                  if view for All CardList check == false ==> only view for card select
            //                  else view for all card in level 1
            /*******************************************************************************************/
            Bill_List_dtb.Clear();
            if ((permission == SUB_LVL) || (permission == OWNER_LVL))
            {
                card_user = " UserName = '" + User_Info.UserName.ToString().Trim() + "'";
                sql_cmd = sql_cmd + " AND (" + card_user + ")";
                if (Bill_Tab_AllCardList.Enabled == true)
                {
                    card_id = " Card_Provider_Name = '" + Bill_Tab_AllCardList.Text.ToString().Trim() + "'";
                    sql_cmd = sql_cmd + " AND (" + card_id + ")";
                }
                if (BillTab_CardOwnerList.Enabled == true)
                {
                    card_user = " UserName = '" + BillTab_CardOwnerList.Text.ToString().Trim() + "'";
                    sql_cmd = sql_cmd + " AND (" + card_user + ")";
                }
            }
            else if (permission == MANAGER_LVL)
            {
                cards_depart = " DEPARTMEMT_NAME = '" + User_Info.Department.ToString().Trim() + "'";
                sql_cmd = sql_cmd + " AND (" + cards_depart + ")";

                if (Bill_Tab_AllCardList.Enabled == true)
                {
                    card_id = " Card_Provider_Name = '" + Bill_Tab_AllCardList.Text.ToString().Trim() + "'";
                    sql_cmd = sql_cmd + " AND (" + card_id + ")";
                }
                if (BillTab_CardOwnerList.Enabled == true)
                {
                    card_user = " UserName = '" + BillTab_CardOwnerList.Text.ToString().Trim() + "'";
                    sql_cmd = sql_cmd + " AND (" + card_user + ")";
                }
            }
            else if (permission == ADMIN_LVL)
            {
                if (Bill_Tab_AllCardList.Enabled == true)
                {
                    card_id = " Card_Provider_Name = '" + Bill_Tab_AllCardList.Text.ToString().Trim() + "'";
                    sql_cmd = sql_cmd + " AND (" + card_id + ")";
                }
                if (BillTab_CardOwnerList.Enabled == true)
                {
                    card_user = " UserName = '" + BillTab_CardOwnerList.Text.ToString().Trim() + "'";
                    sql_cmd = sql_cmd + " AND (" + card_user + ")";
                }
            }
            else
            {
                Bill_List_dtb.Clear();
                return;
            }
            if (Bill_Type.SelectedIndex == 1)
            {
                sql_cmd += " AND (Business  = 'Y')";
            }else if (Bill_Type.SelectedIndex == 2)
            {
                sql_cmd += " AND NOT (Business  = 'Y')";
            }

            Bill_List_dtb = Get_SQL_Data(TCA_Database_Conn, sql_cmd, ref Bill_List_da, ref Bill_List_ds);
            dataGridView_View.DataSource = Bill_List_dtb;
            dataGridView_View.Sort(this.dataGridView_View.Columns[0], ListSortDirection.Ascending);
            Report_Finance();
        }

        private void Report_Finance()
        {
            int total_bill;
            int total_payment;
            int mailinh_cost=0, vina_cost=0;
            int total_fee = 0, total_other_fee = 0;
            int business_fee = 0, persnal_fee = 0;
            

            total_bill = Bill_List_dtb.Rows.Count;
            Total_Bill_Lbl.Text = "Number of Bill: " + total_bill;

            foreach (DataRow row in Bill_List_dtb.Rows)
            {
                if (row["Fee"] != DBNull.Value)
                {
                    total_fee += Convert.ToInt32(row["Fee"]);

                    // Calculate Vinasun & maiLinh Cost
                    if (row["Taxi_Provider_Name"].ToString().Trim() == "MaiLinh")
                    {
                        mailinh_cost += Convert.ToInt32(row["Fee"]);
                    }
                    else if (row["Taxi_Provider_Name"].ToString().Trim() == "VinaSun")
                    {
                        vina_cost += Convert.ToInt32(row["Fee"]);
                    }
                    else
                    {
                        MessageBox.Show("Has no Taxi Provider Name", "Error");
                    }
                }
                if (row["Others_Fee"] != DBNull.Value)
                {
                    total_other_fee += Convert.ToInt32(row["Others_Fee"]);

                    // Calculate Vinasun & maiLinh Cost
                    if (row["Taxi_Provider_Name"].ToString().Trim() == "MaiLinh")
                    {
                        mailinh_cost += Convert.ToInt32(row["Others_Fee"]);
                    }
                    else if (row["Taxi_Provider_Name"].ToString().Trim() == "VinaSun")
                    {
                        vina_cost += Convert.ToInt32(row["Others_Fee"]);
                    }
                    else
                    {
                        MessageBox.Show("Has no Taxi Provider Name", "Error");
                    }
                }

                // Business fee & personal fee
                if (row["Business"] != DBNull.Value)
                {
                    if (row["Business"].ToString().Trim() == "Y")
                    {
                        if (row["Fee"] != DBNull.Value)
                        {
                            business_fee += Convert.ToInt32(row["Fee"]);
                        }
                        if (row["Others_Fee"] != DBNull.Value)
                        {
                            business_fee += Convert.ToInt32(row["Others_Fee"]);
                        }
                    }
                    else
                    {
                        if (row["Fee"] != DBNull.Value)
                        {
                            persnal_fee += Convert.ToInt32(row["Fee"]);
                        }
                        if (row["Others_Fee"] != DBNull.Value)
                        {
                            persnal_fee += Convert.ToInt32(row["Others_Fee"]);
                        }
                    }
                }
            }

            total_payment = total_fee + total_other_fee;
            Total_Cost_Lbl.Text = "Total Cost: " + total_payment.ToString("N2");
            Business_Cost.Text = "Business: " + business_fee.ToString("N2");
            Personal_Cost.Text = "Personal: " + persnal_fee.ToString("N2");
            BillTab_MaiLinh_Cost_Lbl.Text = "Mai Linh: " + mailinh_cost.ToString("N2");
            BillTab_VinaSun_Cost_Lbl.Text = "VinaSun: " + vina_cost.ToString("N2");
        }

        /// <summary>
        /// Name: Load_AddNew_Bill
        /// Function:  
        ///         + Load Card list relate to user account
        ///         + Load Taxi list relate to user account
        /// </summary>
        private void Load_AddNew_Bill()
        {
            Update_BT_Status();
            Load_Taxi_List();
            Load_Card_List_EachProvider();               
        }

        private void Update_BT_Status()
        {
            Add_BT.Enabled = false;
            Update_BT.Enabled = false;
            Approve_BT.Enabled = false;

            if (Is_Completed_bill_info() == true)
            {
                if (Is_new_Bill() == true)
                {
                    Add_BT.Enabled = true;
                }
                else
                {
                    if (Is_Bill_Locked() == false)
                    {
                        if (Is_Bill_approved() == true)
                        {
                            if ((User_Info.Permission == ADMIN_LVL) || (User_Info.Permission  == MANAGER_LVL))
                            {
                                Update_BT.Enabled = true;
                            }
                        }
                        else
                        {
                            Update_BT.Enabled = true;
                            if ((User_Info.Permission == ADMIN_LVL) || (User_Info.Permission == MANAGER_LVL))
                            {
                                Approve_BT.Enabled = true;
                            }
                        }
                    }
                }
            }

            // for Lock bill
            if (User_Info.Permission == ADMIN_LVL)
            {
                LockAll_BT.Visible = true;
                UnLock_BT.Visible = true;
            }
            else {
                LockAll_BT.Visible = false;
                UnLock_BT.Visible = false;
            }

            // for approve all bill
            if ((User_Info.Permission == ADMIN_LVL) || (User_Info.Permission == MANAGER_LVL))
            {
                ApproveAll_BT.Visible = true;
            }
            else
            {
                ApproveAll_BT.Visible = false;
            }
        }

        /// <summary>
        /// Name: Is_Completed_bill_info
        /// Function:
        ///         + Check complete fill bill information
        ///         + Update status of label for inform information require
        /// </summary>
        /// <returns></returns>

        private bool Is_Completed_bill_info()
        {
            bool retvar = true;
            ///@NOTE (Kien ##): Add Code for check complete fill bill information
            if (BillNo_txt.Text == "")
            {
                BillNo_Lbl.ForeColor = Color.Red;
                retvar = false;
            }else{
                BillNo_Lbl.ForeColor = Color.Black;
            }

            if (Taxi_comboBox.Text == "")
            {
                TaxiLbl.ForeColor = Color.Red;
                retvar = false;
            }else{
                TaxiLbl.ForeColor = Color.Black;

            }

            if (TaxiFee_txt.Text == "")
            {
                FeeLbl.ForeColor = Color.Red;
                retvar = false;
            }
            else
            {
                FeeLbl.ForeColor = Color.Black;

            }

            //if (Route_txt.Text == "")
            //{
            //    RouteLbl.ForeColor = Color.Red;
            //    retvar = false;
            //}
            //else
            //{
            //    RouteLbl.ForeColor = Color.Black;

            //}
            return retvar;
        }

        private bool Is_new_Bill()
        {
            ///@NOTE (Kien ##): Check this bill has already on List
            string filterExpression;
            DataRow[] bills;
            filterExpression = "Bill_ID = '" + BillNo_txt.Text + "' AND Taxi_Provider_Name = '" + Taxi_comboBox.Text + "'";
            bills = Bill_List_dtb.Select(filterExpression);
            if (bills.Length > 0)
            {
                if (bills.Length != 1)
                {
                    MessageBox.Show("Has more than one bill have same information: \n" + filterExpression, "Error");
                    this.Close();
                }
                return false;
            }
            return true;
        }

        private bool Is_Bill_approved()
        {
            ///@NOTE (Kien ##): Check this bill has already on List
            string filterExpression;
            DataRow[] bills;

            filterExpression = "Bill_ID = '" + BillNo_txt.Text + "' AND Taxi_Provider_Name = '" + Taxi_comboBox.Text + "'";
            bills = Bill_List_dtb.Select(filterExpression);
            if (bills.Length > 0)
            {
                if (bills.Length == 1)
                {
                    if (bills[0]["Approved"].ToString().Trim() == "Y")
                    {
                        return true;
                    }
                }else {
                    MessageBox.Show("Has more than one bill have same information: \n" + filterExpression, "Error");
                    this.Close();
                }
            }

            return false;
        }

        private bool Is_Bill_Locked()
        {
            ///@NOTE (Kien ##): Check this bill has already on List
            string filterExpression;
            DataRow[] bills;

            filterExpression = "Bill_ID = '" + BillNo_txt.Text + "' AND Taxi_Provider_Name = '" + Taxi_comboBox.Text + "'";
            bills = Bill_List_dtb.Select(filterExpression);
            if (bills.Length > 0)
            {
                if (bills.Length == 1)
                {
                    if (bills[0]["Locked"].ToString().Trim() == "Y")
                    {
                        return true;
                    }
                }
                else
                {
                    MessageBox.Show("Has more than one bill have same information: \n" + filterExpression, "Error");
                    this.Close();
                }
            }

            return false;
        }

        private void Update_User_BT_Click(object sender, EventArgs e)
        {
            string card_name;
            string user_name;
            string department;
            string locked_str;
            DateTime used_date;
            foreach (DataRow row in Bill_List_dtb.Rows)
            {
                card_name = row["Card_Provider_Name"].ToString().Trim();
                used_date = (DateTime)row["Bill_date"];
                locked_str = row["Locked"] == DBNull.Value ? "" : row["Locked"].ToString().Trim();
                user_name = GetCardUser(card_name, used_date);
                if (user_name == "")
                {
                    if (MessageBox.Show("Do you want to stop now?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        break;
                    }
                }
                if (locked_str != "Y")
                {
                    row["UserName"] = user_name;
                    department = GetDepartment(user_name);
                    row["DEPARTMEMT_NAME"] = department;
                }
                else 
                {
                    // break;
                }
            }
            MessageBox.Show("Complete Update User for All Bill","Successful");
        }
    }
}
